/*
 * Copyright (c) 2017, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.wsonrpc.core;

import net.apexes.wsonrpc.json.JsonRpcRequest;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
class ServiceMethodInvoker {

    private final Object instance;
    private final Set<Method> methods;
    private Method method;
    private Object[] args;

    ServiceMethodInvoker(Object instance, Set<Method> methods) {
        this.instance = instance;
        this.methods = methods;
    }

    boolean validateParameters(JsonRpcRequest request) {
        this.args = null;
        this.method = null;
        for (Method m : methods) {
            if (m.getParameterTypes().length != request.getParamCount()) {
                continue;
            }
            Object[] params = request.getParams(m.getGenericParameterTypes());
            if (params != null) {
                this.method = m;
                this.args = params;
                break;
            }
        }
        return method != null;
    }

    Object invoke() throws Exception {
        return method.invoke(instance, args);
    }

}
